package com.junjie.blibli.api;

import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
public class RestfulApi {
    private final Map<Integer,Map<String,Object>> dataMap;

    public RestfulApi(){
        dataMap = new HashMap<>();
        for(int i=0;i<3;i++){
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",i);
            map.put("name","name"+i);
            dataMap.put(i,map);
        }
    }

    @GetMapping("/objects/{id}")
    public Map<String,Object> getData(@PathVariable Integer id){
        return dataMap.get(id);
    }

    @DeleteMapping("/objects/{id}")
    public String deleteData(@PathVariable Integer id){
        dataMap.remove(id);
        return "delete Success";
    }

    @PostMapping("/objects")
    public String postData(@RequestBody Map<String,Object> data){
        Integer[] idArray = dataMap.keySet().toArray(new Integer[0]);
        Arrays.sort(idArray);
        int nextId = idArray[idArray.length-1]+1;
        dataMap.put(nextId,data);
        return "post Success";
    }

    @PutMapping("/objects")
    public String putData(@RequestBody Map<String,Object> data){
        Integer id = Integer.valueOf(String.valueOf(data.get("id")));
        Map<String, Object> containData = dataMap.get(id);
        if(containData==null){
            Integer[] idArray = dataMap.keySet().toArray(new Integer[0]);
            Arrays.sort(idArray);
            int nextId = idArray[idArray.length-1]+1;
            dataMap.put(nextId,data);
        }else{
            dataMap.put(id,data);
        }
        return "put Success";
    }

}
